package com.yuzhihao.writejvm.constant;

import com.yuzhihao.writejvm.clazz.ClassInfo;
import com.yuzhihao.writejvm.format.MethodTypeResolutionEnum;
import com.yuzhihao.writejvm.format.PrintFormat;
import com.yuzhihao.writejvm.read.Parse;
import com.yuzhihao.writejvm.read.ReadClassFileFatory;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.log4j.Log4j2;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 *
 * The CONSTANT_MethodHandle_info Structure
 *
 * @author yzh
 * @since  2021年12月01日19:18:52
 */

@Data
@Log4j2
@EqualsAndHashCode(callSuper = true)
public class ConstantMethodHandleInfo extends ConstantPool{

    private int reference_kind_u1 = 1;

    private int reference_kind;

    private int reference_index_u2 = 2;

    private int reference_index;

    private String constant;

    private MethodTypeResolutionEnum handle;

    public ConstantMethodHandleInfo(Map<String,ConstantPool> pools) {
        super(pools);
        super.name = "MethodHandle";
    }

    @Override
    public void parse(DataInputStream dis, ClassInfo ci) {
        try {
            this.reference_kind = Parse.byteToInt(reference_kind_u1, dis);
            this.reference_index = Parse.byteToInt(reference_index_u2, dis);
            this.handle = ReadClassFileFatory.method_handle_instance(this.reference_kind);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    @Override
    public String getConstant() {
        if(Objects.nonNull(this.constant)){
            return this.constant;
        }

        ConstantPool cp = pools.get(String.valueOf(reference_index));
        this.constant = cp.getConstant();

        return constant;
    }

    @Override
    public String print() {
        StringBuilder builder = new StringBuilder();

        builder.append(PrintFormat.MEMPTY).append(PrintFormat.HASHTAG)
                .append(reference_index)
                .append(PrintFormat.MEMPTY);

        builder.append(PrintFormat.DOUBLE_SLASH)
                .append(PrintFormat.EMPTY)
                .append(this.getConstant());

        return builder.toString();
    }

}
